(function( w, d, z , $, t ){

    var // 存储搜索图书请求的延时句柄
        queue,

        // 图书基本信息模版
        tp1 = document.getElementById( 'tp1' ).textContent,

        // 图书详细信息模版
        tp2 = document.getElementById( 'tp2' ).textContent,

        // 7牛域名，现在使用我的
        // ##TODO
        domain = 'http://7xla0q.com1.z0.glb.clouddn.com/lpic/',

        // 包含所有图书的dom
        $dookdom = z( '#search-allbooks' ),

        // 每次渲染图书基本信息后的最后一本书，用来判断是否加载下一页
        lastdom = {},

        // 搜索总页数, 当前页数, 搜索关键词
        allpage, nowpage, keywords;

    z( '.search-input' ).on( 'input', function(){

        var keyword = this.value;

        z( '#search-allbooks' ).empty();

        clearTimeout( queue );

        if( ! keyword ){
            $( '.search-user-prompt' ).show();
            $( '.search-searching' ).hide();
            return true;
        }

        $( '.search-user-prompt' ).hide();
        $( '.search-searching' ).show();

        queue = setTimeout(function(){

            z.ajax({
                'url': 'http://xiyou.changxiaoyuan.com/test/?callback=JSON_CALLBACK',
                'data': {
                    'w': keyword,
                    'do':'querybook',
                    'appkey':'4107762472'
                },
                'dataType': 'jsonp',
                'cache': true,
                'success': function( data ){
                    z( '<p class="search-info">共搜索到' + data.all + '条结果，共' + data.allpage + '页。</p>' )
                        .appendTo( '#search-allbooks' );

                    render_books( data );
                }
            })

        }, 700);
    });

    z( w ).on( 'scroll', function(){

        if( nowpage >= allpage ) return true;

        if( lastdom.getBoundingClientRect().bottom - w.innerHeight < 160 && !$( 'body' ).lock() ){
            var nextpage = nowpage + 1,
                nextpageinfo = z( '<p class="search-next-info">正在加载第' + nextpage + '页...</p>' );

            nextpageinfo.appendTo( '#search-allbooks' );
            $( 'body' ).lock( true );
            z.ajax({
                'url': 'http://xiyou.changxiaoyuan.com/test/?callback=JSON_CALLBACK',
                'data': {
                    'w': keywords,
                    'do':'querybook',
                    'page': nextpage,
                    'appkey':'4107762472'
                },
                'dataType': 'jsonp',
                'cache': true,
                'success': function( data ){
                    $( 'body' ).lock( false );
                    nextpageinfo.remove();
                    render_books( data );
                }
            });
        }
    });

    z( '#search-allbooks' ).on( 'click', function( e ){

        var from_eachbook = t.is_from( e, 'search-each-book' );

        console.log(from_eachbook)

        if( from_eachbook ){

            var dom = z( from_eachbook )
                detailid = dom.attr( 'data-detail' ),
                isbn = dom.attr( 'data-isbn' ),
                nextele = dom.next();

            if( nextele.hasClass( 'search-book-detail-box' ) ){
                if( nextele.hasClass( 'hide' ) ){
                    nextele.removeClass( 'hide' );
                }else{
                    nextele.addClass( 'hide' );
                }
                return true;
            }

            if( $( from_eachbook ).lock() ){
                return false;
            }

            var tmpinfo = z('<p class="search-tmp-info">正在加载详细信息...</p>');
            dom.after( tmpinfo );

            $( from_eachbook ).lock( true );

            z.ajax({
                'url': 'http://xiyou.changxiaoyuan.com/test/?callback=JSON_CALLBACK',
                'data': {
                    'ctrlid': detailid,
                    'do': 'querydetail',
                    'isbn': isbn,
                    'appkey': 4107762472
                },
                'dataType': 'jsonp',
                'cache': true,
                'success': function( data ){
                    tmpinfo.remove();
                    dom.after(t.render( [data], tp2,
                            ['detailid', 'isbn', 'ca_all', 'ca_on', 'ca_shuku', 'yt_all', 'yt_on'],
                            function( item ){
                                item.isbn = isbn;
                                item.ca_all = item.changan.all;
                                item.ca_on = item.changan.on;
                                item.ca_shuku = item.changan.shuku.replace(/\（.*/g,'');
                                item.yt_all = item.yanta.all;
                                item.yt_on = item.yanta.all;
                                return item;
                        }) );
                }
            })

        }

    });

    // 生成搜索出来的图书的hmtl
    function render_books( data ){
        var allbooks = z(t.render( data.result,
                            tp1,
                            ['detail', 'src', 'title', 'author', 'year', 'press', 'isbn'],
                            function( item ){

            item.src = domain + item.isbn.replace(/-/g, '');

            return item;
        }));

        lastdom = allbooks[allbooks.length - 1];

        $( '.search-searching' ).hide();

        $dookdom.append( allbooks );

        allpage = data.allpage * 1;
        nowpage = data.nowpage * 1;
        keywords = data.keywords;
    }

    w.loaderr = function(e){

        var target = e.target,
            isbn = e.target.getAttribute('data-isbn');

        $( target ).hide();

        z.ajax({
            'url': 'http://getimg.changxiaoyuan.com/?isbn=' + isbn.replace(/\-/g, ''),
            'success': function( data ){
                $( target ).set('src', 'http://' + data.url).show();
            }
        })
    }


})( window, document, Zepto , function( selector ){

    function select( s ){
        if( typeof s === 'object' ){
            this.e = s;
        }else{
            this.e = document.querySelector( s );
        }
        this.cls = this.e === null ? null : this.e.classList;
    }

    // 元素的锁，参数为true加锁，参数为false解锁，不加参数返回锁状态
    select.prototype.lock = function(type){

        if( type === true ){
            this.e.setAttribute( 'data-lock', 'true' );
        }else if( type === false ){
            this.e.removeAttribute( 'data-lock' );
        }else{
            return !! this.e.getAttribute( 'data-lock' );
        }

    }

    select.prototype.set = function(k, v){
        this.e.setAttribute(k,v);
        return this;
    }

    // 隐藏显示
    select.prototype.hide = function(){
        this.cls.add( 'hide' );
        return this.e;
    }

    select.prototype.show = function(){
        this.cls.remove( 'hide' );
        return this.e;
    }

    return new select( selector );
}, {

    // 渲染html
    'render': function( data, tp, args, dataFilter, tmplFilter){
        var result = [];

        data.forEach(function( item ){

            var t = tp;

            if( dataFilter ) item = dataFilter( item );

            args.forEach(function( arg ){
                t = t.replace(new RegExp("{{" + arg + "}}", "g"), item[arg]);
            });

            if( tmplFilter ) t = tmplFilter( t, item );

            result.push( t );
        });

        return result.join('');
    },

    // 通过e.path中元素冒泡顺序是否包含指定类判断事件委托的点击来源
    'is_from': function( e, class_name ){

        var isfrom = false;

        function querybyclass( ele ){
            var has = ele.className.indexOf( class_name );
            if( ele.nodeName === 'BODY' ) return false;

            if( has !== -1 ){
                isfrom = ele;
                return false;
            }else if( has === -1 ){
                querybyclass( ele.parentElement );
            }
        }

        querybyclass( e.target );

        return isfrom;

    }
});
